package amartin47;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.StringTokenizer;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TextLayoutCenter extends JPanel {
	
	
	 public TextLayoutCenter() {
		super();
		this.setBackground(Color.BLACK);
		f =  new Font("Arial", Font.BOLD, 40);
	}
  Dimension d;
  Font f;
  FontMetrics fm;
  int fh, ascent;
  BufferedImage bufferedImage;
  int space;
  String toTokenize = "Failed to connect to Slide Selector program";

  public static void main(String[] a) {
     
	  
    JFrame f = new JFrame();
    f.setSize(300, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new TextLayoutCenter());
    f.setVisible(true);
  }
  
  public void setFont(Font f)
  {
	  this.f = f;
  }
  
  public void updateString(String s){
	  toTokenize = s;
	  repaint();
  }
  
  protected void paintComponent(Graphics gW) {
	super.paintComponent(gW);
    d = getSize();

    bufferedImage = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
    
    Graphics2D g = bufferedImage.createGraphics();
    g.setFont(f);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    
	  fm = g.getFontMetrics();
	  ascent = fm.getAscent();
	  fh = ascent + fm.getDescent();
	  space = fm.stringWidth(" ");
    
    g.setColor(Color.WHITE);
    StringTokenizer st = new StringTokenizer(toTokenize);
    int x = 0;
    int nextx;
    int y = 0;
    String word, sp;
    int wordCount = 0;
    String line = "";
    while (st.hasMoreTokens()) {
      word = st.nextToken();
      if (word.toLowerCase().equals("<br>")) {
        drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
        line = "";
        wordCount = 0;
        x = 0;
        y = y + (fh * 1);
      } else {
        int w = fm.stringWidth(word);
        if ((nextx = (x + space + w)) > d.width) {
          drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
          line = "";
          wordCount = 0;
          x = 0;
          y = y + fh;
        }
        if (x != 0) {
          sp = " ";
        } else {
          sp = "";
        }
        line = line + sp + word;
        x = x + space + w;
        wordCount++;
      }
    }
    drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
    int yStart = (this.getHeight() - (y + fh)) / 2;
    gW.drawImage(bufferedImage, 0, yStart, this.getWidth(), this.getHeight() - yStart, 0, 0, this.getWidth(), (y + fh), null);
  }

  public void drawString(Graphics g, String line, int wc, int lineW, int y) {
    g.drawString(line, (d.width - lineW) / 2, y);//center
  }
}